import { useState } from "react";

// 受控组件：通过 state 和 change 事件来收集表单数据
function App() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  const handleUsernameChange = (e) => {
    const value = e.target.value.trim();
    setUsername(value);
  };

  const handlePasswordChange = (e) => {
    const value = e.target.value.trim();
    setPassword(value);
  };

  // 高阶函数
  const handleChange = (key) => {
    return (e) => {
      const value = e.target.value.trim();
      if (key === "username") {
        setUsername(value);
      } else if (key === "password") {
        setPassword(value);
      }
    };
  };

  return (
    <>
      <h1>App</h1>
      <form>
        用户名:
        {/* <input type="text" value={username} onChange={handleUsernameChange} /> */}
        <input
          type="text"
          value={username}
          onChange={handleChange("username")}
        />
        <br />
        密码:
        {/* <input
          type="password"
          value={password}
          onChange={handlePasswordChange}
        /> */}
        <input
          type="password"
          value={password}
          onChange={handleChange("password")}
        />
      </form>
    </>
  );
}

export default App;
